/*
 * (C) 2009, Elephant Seven Hamburg Gmbh, 
 * Author: Detlev Wiese
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.se and its accompanying notice file is
 * included with the distribution. 
 */ 
package com.e7.streams;

import java.util.NoSuchElementException;

/**
 * A simple stream class, which can only handle Streams with 
 * exactly one element. 
 * @param <E> The type of the element to handle
 */
public class SingleElementStream<E> extends AbstractStream<E> 
{
	private E element; 
	private boolean delivered; 
	
	/**
	 * Create an instance!
	 * @param e The element to deliver. It may be {@code null}, which 
	 * simply means, that the stream will deliver {@code null} as its 
	 * element. 
	 */
	public SingleElementStream(E e) {
		initializeForElement(e); 
	}

	/**
	 * <P>Set the element delivered by the receiver.</P>
	 * <P>Note: by setting the element, the stream-instance will reset
	 * itself! This behavior supports the reuse of SingleElementStream-instances.
	 * </P>
	 * @param e the element to set for delivery
	 */
	public void initializeForElement(E e) {
		this.element = e; 
		this.delivered = false; 
	}

	/**
	 * @return The only element of the receiver
	 */
	public E getElement() {
		return element; 
	}
	
	/**
	 * {@inheritDoc}
	 * @return true, if the element has no yet been delivered through 
	 * {@link SingleElementStream#next()}.
	 */
	public boolean hasNext() {
		return !delivered;
	}
	
	public E next() {
		if (delivered) 
			throw new NoSuchElementException(); 
		else {
			delivered = true; 
			return element;
		}
	}
}
